import React, { useEffect, useState, useRef } from 'react';
import {
  ArrowLeftOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined,
  BorderOutlined,
} from '@ant-design/icons';
import {
  VideoMonitorDetailApi,
  VideoMonitorTreeApi,
  VideoMonitorLastPullApi,
  type SysCameraInfo,
} from '@/api/videoMonitorApi';
import { useRouter, useRoute } from '@/hooks/useRouter';
import HlsPlayer from '../utils/HlsPlayer';
import { Input, Tree, Button } from 'antd';
import type { DataNode } from 'antd/es/tree';
import './index.scss';

/**
 * 视频监控详情页面
 * 提供视频监控的实时查看功能
 */
const VideoMonitorDetail: React.FC = () => {
  // 路由导航
  const { navigate } = useRouter();
  const route = useRoute();
  const monitorId = route.query.id;

  // 状态管理
  const [_loading, setLoading] = useState<boolean>(true);
  const [monitorDetail, setMonitorDetail] = useState<SysCameraInfo | null>(null);
  const [treeData, setTreeData] = useState<DataNode[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [activeKey, setActiveKey] = useState<1 | 2 | 3 | 4>(2); // 默认2x2布局
  const [isFullScreen, setIsFullScreen] = useState<boolean>(false);
  const [playerIds, setPlayerIds] = useState<number[]>([]);
  const [slotKeys, setSlotKeys] = useState<
    Array<{
      key?: string;
      pullFlowUrl?: string;
      id?: number;
      name?: string;
    }>
  >([]);
  const [_currentSlot, setCurrentSlot] = useState<number>(0);
  const [needInitPlayer, setNeedInitPlayer] = useState<boolean>(false);

  // 引用
  const viewWrapRef = useRef<HTMLDivElement>(null);
  const playerRefs = useRef<{ [key: number]: HlsPlayer | null }>({});

  // 初始化播放器
  useEffect(() => {
    if (monitorDetail?.pullFlowUrl && monitorDetail.id && playerRefs.current[monitorDetail.id]) {
      playerRefs.current[monitorDetail.id]?.initPlayer(monitorDetail.pullFlowUrl);
    }
  }, [monitorDetail]);

  const findParentKeys = (data: DataNode[], targetKey: React.Key): React.Key[] => {
    for (const node of data) {
      if (node.children) {
        if (node.children.some(child => child.key === targetKey)) {
          return [node.key];
        }
        const found = findParentKeys(node.children, targetKey);
        if (found.length > 0) {
          return [node.key, ...found];
        }
      }
    }
    return [];
  };

  /**
   * 获取视频监控详情
   */
  const fetchMonitorDetail = async () => {
    if (!monitorId) {
      window.$message.error('监控ID不存在');
      return;
    }

    try {
      setLoading(true);
      const res = await VideoMonitorDetailApi({ id: Number(monitorId) });
      if (res.success && res.data) {
        setMonitorDetail(res.data);
        setSelectedKeys([res.data.id as React.Key]);

        // 更新最新拉流时间
        VideoMonitorLastPullApi({ id: Number(monitorId) });

        return res.data;
      } else {
        window.$message.error(res.message || '获取监控详情失败');
      }
    } catch (error) {
      console.error('获取监控详情失败:', error);
      window.$message.error('获取监控详情失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  /**
   * 获取视频监控树形结构
   */
  const fetchMonitorTree = async () => {
    try {
      const res = await VideoMonitorTreeApi({});
      if (res.success && res.data) {
        // 处理树形结构数据
        const treeData: DataNode[] = Object.keys(res.data).map((key, index) => {
          return {
            title: key,
            key: `group-${index}`,
            kind: 0, // 分组
            children: (res.data as any)[key].map((item: SysCameraInfo) => {
              return {
                ...item,
                title: item.name,
                key: item.id as number,
                kind: 1, // 摄像头
              };
            }),
          };
        });
        setTreeData(treeData);
        return treeData;
      } else {
        window.$message.error(res.message || '获取监控分组失败');
      }
    } catch (error) {
      console.error('获取监控分组失败:', error);
      window.$message.error('获取监控分组失败，请稍后重试');
    }
  };

  /**
   * 选择视频监控
   */
  const handleSelectVideo = (_keys: React.Key[], info: any) => {
    const node = info.node;
    if (node.kind !== 1) return; // 只处理摄像头节点

    setSelectedKeys([node.key]);

    // 更新最新拉流时间
    if (node.id) {
      VideoMonitorLastPullApi({ id: node.id });
    }

    // 查找空槽位或第一个槽位
    let targetSlotIndex = slotKeys.findIndex(slot => !slot.id);
    if (targetSlotIndex === -1) {
      targetSlotIndex = 0; // 如果没有空槽位，则替换第一个槽位
    }

    // 更新槽位信息
    const newSlotKeys = [...slotKeys];
    newSlotKeys[targetSlotIndex] = {
      key: newSlotKeys[targetSlotIndex].key,
      pullFlowUrl: node.pullFlowUrl,
      id: node.id,
      name: node.name,
    };
    setSlotKeys(newSlotKeys);

    // 如果该节点已经在播放列表中，更新播放器
    if (node.id && playerIds.includes(node.id)) {
      // 重新初始化播放器
      if (node.pullFlowUrl && playerRefs.current[node.id]) {
        playerRefs.current[node.id]?.initPlayer(node.pullFlowUrl);
      }
      return;
    }

    // 添加到播放列表
    if (node.id) {
      const newPlayerIds = [...playerIds, node.id];
      setPlayerIds(newPlayerIds);

      // 标记需要初始化播放器
      setNeedInitPlayer(true);
    }
  };

  /**
   * 切换视图布局
   */
  const handleChangeLayout = (key: number) => {
    if (key === activeKey) return;

    // 保存当前播放状态
    const currentPlayingVideos = slotKeys.filter(slot => slot.id && slot.pullFlowUrl);

    // 保存当前播放器实例
    const currentPlayerRefs = { ...playerRefs.current };

    // 创建新的槽位结构
    const newSlotKeys: Array<{
      key?: string;
      pullFlowUrl?: string;
      id?: number;
      name?: string;
    }> = [];
    const totalSlots = key * key;

    // 保留尽可能多的视频，但不超过新布局的槽数量
    // 从前往后取视频，确保切换到更小布局时取最前面的视频
    const videosToKeep = Math.min(currentPlayingVideos.length, totalSlots);

    for (let i = 0; i < totalSlots; i++) {
      const slotKey = `slot-${i}`;

      if (i < videosToKeep && currentPlayingVideos[i]) {
        // 保留现有的视频信息，按顺序从前往后取
        newSlotKeys.push({
          key: slotKey,
          pullFlowUrl: currentPlayingVideos[i].pullFlowUrl,
          id: currentPlayingVideos[i].id,
          name: currentPlayingVideos[i].name,
        });
      } else {
        // 空槽位
        newSlotKeys.push({
          key: slotKey,
          pullFlowUrl: '',
          id: undefined,
          name: '',
        });
      }
    }

    // 更新状态
    setSlotKeys(newSlotKeys);
    setActiveKey(key as 1 | 2 | 3 | 4);

    // 如果有保留的视频，当前槽位设为第一个有视频的槽位
    setCurrentSlot(videosToKeep > 0 ? 0 : 0);

    // 保持播放器实例引用
    playerRefs.current = currentPlayerRefs;

    // 标记需要重新初始化播放器，确保播放状态保持
    if (videosToKeep > 0) {
      setNeedInitPlayer(true);
    }
  };

  /**
   * 视频全屏播放
   */
  const handleVideoFullscreen = async (videoId: string) => {
    const videoElement = document.getElementById(videoId) as HTMLVideoElement;
    if (!videoElement) return;

    try {
      if (videoElement.requestFullscreen) {
        await videoElement.requestFullscreen();
      } else if ((videoElement as any).webkitRequestFullscreen) {
        await (videoElement as any).webkitRequestFullscreen();
      } else if ((videoElement as any).mozRequestFullScreen) {
        await (videoElement as any).mozRequestFullScreen();
      } else if ((videoElement as any).msRequestFullscreen) {
        await (videoElement as any).msRequestFullscreen();
      }
    } catch (error) {
      console.error('视频全屏失败:', error);
    }
  };

  /**
   * 切换全屏
   */
  const handleToggleFullScreen = async () => {
    if (!viewWrapRef.current) return;

    try {
      if (!isFullScreen) {
        if (viewWrapRef.current.requestFullscreen) {
          await viewWrapRef.current.requestFullscreen();
        }
      } else {
        if (document.exitFullscreen) {
          await document.exitFullscreen();
        }
      }
    } catch (error) {
      console.error('全屏操作失败:', error);
    }
  };

  /**
   * 返回列表页
   */
  const handleBack = () => {
    navigate('/video/monitor');
  };

  /**
   * 初始化视频槽位
   */
  const initSlotKeys = (key: number) => {
    const newSlotKeys: Array<{
      key?: string;
      pullFlowUrl?: string;
      id?: number;
      name?: string;
    }> = [];
    for (let i = 0; i < key * key; i++) {
      const slotKey = `slot-${i}`;
      newSlotKeys.push({
        key: slotKey,
        pullFlowUrl: '',
        id: undefined,
        name: '',
      });
    }
    setSlotKeys(newSlotKeys);
  };

  /**
   * 监听全屏变化
   */
  const handleFullScreenChange = () => {
    const isFullScreenNow = !!(document.fullscreenElement || 
                              (document as any).webkitFullscreenElement || 
                              (document as any).mozFullScreenElement || 
                              (document as any).msFullscreenElement);
    setIsFullScreen(isFullScreenNow);
  };

  // 初始化
  useEffect(() => {
    const initPage = async () => {
      // 并行获取监控详情和树形结构
      const [detailData, treeData] = await Promise.all([fetchMonitorDetail(), fetchMonitorTree()]);

      // 如果有监控详情和树形结构数据，则计算需要展开的节点
      if (detailData && treeData) {
        const parentKeys = findParentKeys(treeData, detailData.id as React.Key);
        setExpandedKeys(parentKeys);
      }
    };

    initPage();

    // 添加全屏变化监听
    const fullscreenChangeEvents = [
      'fullscreenchange',
      'webkitfullscreenchange',
      'mozfullscreenchange',
      'MSFullscreenChange'
    ];
    
    const addFullScreenListeners = () => {
      fullscreenChangeEvents.forEach(event => {
        document.addEventListener(event, handleFullScreenChange);
      });
    };

    const removeFullScreenListeners = () => {
      fullscreenChangeEvents.forEach(event => {
        document.removeEventListener(event, handleFullScreenChange);
      });
    };

    addFullScreenListeners();

    // 添加 HLS.js 脚本
    if (!document.getElementById('hls-script')) {
      const script = document.createElement('script');
      script.id = 'hls-script';
      script.src = 'https://cdn.jsdelivr.net/npm/hls.js@latest';
      script.async = true;
      document.head.appendChild(script);
    }

    return () => {
      // 清理全屏变化监听
      removeFullScreenListeners();

      // 清理播放器实例
      Object.values(playerRefs.current).forEach(player => {
        if (player) {
          player.destroy();
        }
      });
      
      // 退出全屏状态
      if (isFullScreen) {
        handleToggleFullScreen();
      }
    };
  }, [monitorId]);

  // 初始化时设置默认布局的槽位
  useEffect(() => {
    if (slotKeys.length === 0) {
      initSlotKeys(activeKey);
    }
  }, []);

  // 监听是否需要初始化播放器
  useEffect(() => {
    if (!needInitPlayer) return;

    // 为每个有视频流的槽位创建或更新播放器实例
    slotKeys.forEach((slot, index) => {
      if (slot.id && slot.pullFlowUrl) {
        const videoId = `video-player-${slot.id}`;

        // 等待DOM更新后再初始化播放器
        setTimeout(() => {
          const videoElement = document.getElementById(videoId);
          if (videoElement) {
            // 如果播放器实例不存在，则创建新的
            if (!playerRefs.current[slot.id!]) {
              playerRefs.current[slot.id!] = new HlsPlayer(videoId, {
                onStatusChange: status => {
                  console.log(`Player ${slot.id} status: ${status}`);
                },
              });
            }

            // 延迟初始化播放器并加载视频流，避免播放冲突
            setTimeout(() => {
              playerRefs.current[slot.id!]?.initPlayer(slot.pullFlowUrl!);
            }, index * 150); // 为每个视频添加不同的延迟，避免同时播放冲突
          }
        }, 100);
      }
    });

    // 重置标记
    setNeedInitPlayer(false);
  }, [needInitPlayer, slotKeys]);

  return (
    <div className="page-wrapper">
      <div className="page-title">
        <div className="page-main-title">
          <ArrowLeftOutlined className="back-icon" onClick={handleBack} />
          视频监控详情
        </div>
        <div className="page-sub-title">{monitorDetail?.name || '加载中...'}</div>
      </div>

      <div className="page-content-box">
        <div className="page-content flex show-bg">
          <div className="monitor-container">
            <div className="monitor-sidebar">
              <Input.Search
                placeholder="请输入设备名称"
                style={{ width: '100%', marginBottom: '16px' }}
                onSearch={(_value: string) => {
                  // 实现搜索功能
                }}
              />
              <div className="monitor-tree">
                <Tree
                  treeData={treeData}
                  selectedKeys={selectedKeys}
                  expandedKeys={expandedKeys}
                  onSelect={handleSelectVideo}
                  onExpand={(keys: React.Key[]) => setExpandedKeys(keys)}
                />
              </div>
            </div>

            <div
              className={`monitor-view-wrap ${isFullScreen ? 'fullscreen' : ''}`}
              ref={viewWrapRef}
            >
              <div className="monitor-view-content">
                {slotKeys.map((slot, _index) => (
                  <div
                    key={slot.key}
                    className={`monitor-view-item ${selectedKeys.includes(slot.id || '') ? 'highlight' : ''}`}
                    style={{
                      width: `${100 / activeKey}%`,
                      height: `${100 / activeKey}%`,
                    }}
                  >
                    {slot.pullFlowUrl ? (
                      <div className="monitor-player">
                        <div className="player-title">
                          {slot.name || '未命名'}
                          <Button
                            type="link"
                            size="small"
                            icon={<BorderOutlined />}
                            onClick={() => handleVideoFullscreen(`video-player-${slot.id}`)}
                            style={{ float: 'right', color: '#fff' }}
                            title="全屏播放"
                          />
                        </div>
                        <div className="player-content">
                          <video
                            id={`video-player-${slot.id}`}
                            className="video-element"
                            autoPlay
                            muted
                            playsInline
                          />
                        </div>
                      </div>
                    ) : (
                      <div className="monitor-empty">暂无视频</div>
                    )}
                  </div>
                ))}
              </div>

              <div className="monitor-view-controls">
                <div className="layout-controls">
                  <Button
                    type={activeKey === 1 ? 'primary' : 'default'}
                    onClick={() => handleChangeLayout(1)}
                  >
                    1×1
                  </Button>
                  <Button
                    type={activeKey === 2 ? 'primary' : 'default'}
                    onClick={() => handleChangeLayout(2)}
                  >
                    2×2
                  </Button>
                  <Button
                    type={activeKey === 3 ? 'primary' : 'default'}
                    onClick={() => handleChangeLayout(3)}
                  >
                    3×3
                  </Button>
                  <Button
                    type={activeKey === 4 ? 'primary' : 'default'}
                    onClick={() => handleChangeLayout(4)}
                  >
                    4×4
                  </Button>
                </div>

                <Button
                  icon={isFullScreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
                  onClick={handleToggleFullScreen}
                >
                  {isFullScreen ? '退出全屏' : '全屏'}
                </Button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default VideoMonitorDetail;